package com.isay.frameworklib.okhttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by cywu4 on 2018/12/17.
 */
public class BaseHttpManager {

    private static OkHttpClient mHttpClient;

    public static OkHttpClient getInstance() {
        if (mHttpClient == null) {
            synchronized (BaseHttpManager.class) {
                if (mHttpClient == null) {
                    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(20, TimeUnit.SECONDS)
                            .readTimeout(20, TimeUnit.SECONDS)
                            .addNetworkInterceptor(new RequestInterceptor());
                    mHttpClient = builder.build();
                }
            }
        }
        return mHttpClient;
    }


    /**
     * get请求
     *
     * @param url
     * @param ICommonCallback
     */
    public static void get(String url, Map<String, String> params, Object tag, final ICommonCallback ICommonCallback) {
        Request request = HttpRequest.getRequestForGet(url, params, tag);
        Call call = getInstance().newCall(request);
        call.enqueue(new HttpCallBack(ICommonCallback));
    }


    /**
     * post请求
     */
    public static void post(final String url, final Map<String, Object> params, final Object tag, final ICommonCallback ICommonCallback) {
        Request request = HttpRequest.getRequestForPost(url, params, tag);
        Call call = getInstance().newCall(request);
        call.enqueue(new HttpCallBack(ICommonCallback));
    }


    /**
     * 根据tag标签取消网络请求
     *
     * @param tag
     */
    public static void cancelTag(Object tag) {
        if (tag == null) {
            return;
        }
        for (Call call : getInstance().dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : getInstance().dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }

    /**
     * 取消所有请求请求
     */
    public static void cancelAll() {
        for (Call call : getInstance().dispatcher().queuedCalls()) {
            call.cancel();
        }
        for (Call call : getInstance().dispatcher().runningCalls()) {
            call.cancel();
        }
    }

}
